<template>
  <div class="otcoptionWrapper">

    <div class="app-container">
      <el-row :gutter="12">
        <el-col :span="4">
          <el-form-item label="定价配置" label-width="68px">
            <baseCombox url="/pricing/comboBox/queryPriceCfg4Local.action"
                        :queryParam="queryParamCfg"
                        ref="mainCfgIdRef"
                        prop="cfgId"
                        @change="handleCfgIdChange"
                        clearable @defaultSelect="(value) => {defaultSelectCfgId = value}"
                        :defaultSelectIndex="'0'"
                        :style="{width:'100%'}"
                        valueField="cfgId"
                        labelField="name"
                        size="small"
                        placeholder="定价配置" v-model="queryConfigParams.cfgId"></baseCombox>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" icon="Search" size="small" style="margin: 3px 3px"
                     v-hasPermi="['pricingconfig:otcoptionAndTarget:list']"
                     @click="handleContractCfgQuery">搜索
          </el-button>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="8">
          <el-button
              type="primary"
              icon="Plus"
              style="margin: 3px 3px"
              size="small"
              :disabled="cfgSelectDisabled"
              @click="handleContractAdd"
              v-hasPermi="['pricingconfig:otcoption:contractadd']"
          >新增
          </el-button>
          <el-button
              type="success"
              icon="Edit"
              size="small"
              style="margin: 3px 3px"
              :disabled="single"
              @click="handleContractUpdate"
              v-hasPermi="['pricingconfig:otcoption:contractedit']"
          >修改
          </el-button>

          <el-button
              type="danger"
              icon="Delete"
              size="small"
              style="margin: 3px 3px"
              :disabled="single"
              @click="handleContractDelete"
              v-hasPermi="['pricingconfig:otcoption:contractremove']"
          >删除
          </el-button>
        </el-col>
      </el-row>
      <xTable ref="refContractTable"
              v-loading="loading"
              :data="contractList"
              multiple="false"
              refId="refContractTable"
              @selection-change="handleContractSelectionChange"
              class="tableDragger"

      >
        <template #columList>
          <el-table-column label="序号" type="index" width="50" />
          <el-table-column align="left" label="定价配置代码" prop="CFG_ID" width="120"></el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="left" label="定价配置名称" width="150"
                           prop="CFG_NAME"></el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="left" label="合约编号" width="140"
                           prop="I_CODE"></el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="left" label="期权类型" width="120"
                           prop="PRODUCT_TYPE">
            <template #default="scope">
              <dict-tag :options="optionType" :value="scope.row.PRODUCT_TYPE" spVal='*'/>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="left" label="标的代码" width="150"
                           prop="U_I_CODE">
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="left" label="资产类型" width="120"
                           prop="U_A_TYPE">
            <template #default="scope">
              <dict-tag :options="A_TYPE" :value="scope.row.U_A_TYPE" spVal='*'/>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="left" label="标的名称" width="150"
                           prop="U_I_NAME"></el-table-column>
          <el-table-column v-if="false" :show-overflow-tooltip="true" align="left" label="计算组件" width="180"
                           prop="PP_CODE"></el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="left" label="计算组件" width="120"
                           prop="PP_NAME"></el-table-column>
          <el-table-column v-if="false" :show-overflow-tooltip="true" align="left" width="120"
                           label="市场计算函数入口" prop="DLL_ENTRY"></el-table-column>
          <el-table-column v-if="false" :show-overflow-tooltip="true" align="left" width="120"
                           label="现金流函数入口" prop="DLL_ENTRY_CF"></el-table-column>
          <el-table-column v-if="false" :show-overflow-tooltip="true" align="left" width="120"
                           label="事件函数入口" prop="DLL_ENTRY_EVENT"></el-table-column>
          <el-table-column v-if="false" :show-overflow-tooltip="true" align="left" label="无风险利率类型" width="200"
                           prop="DIS_TYPE"></el-table-column>
          <el-table-column v-if="false" :show-overflow-tooltip="true" align="left" label="DIS_VALUE" width="120"
                           prop="DIS_VALUE">
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="right" label="无风险利率(%)"
                           prop="DIS_NAME">
            <template #default="scope">
              <span>{{
                  scope.row.DIS_TYPE == 0 ? proxy.lsh.multiply(scope.row.DIS_VALUE, 100).toFixed(3) : scope.row.DIS_NAME
                }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="false" align="left" label="无风险利率计息基准" prop="DIS_DAYCOUNT" width="120"></el-table-column>
        </template>
      </xTable>
      <pagination
          class="pagination-container1"
          v-show="contractTotal>0"
          :total="contractTotal"
          v-model:page="queryConfigParams.pageNum"
          v-model:limit="queryConfigParams.pageSize"
          @pagination="getContractCfgList"
      />
    </div>
    <el-divider content-position="center"></el-divider>

    <div class="app-container">
      <div>
        <el-button
            type="primary"
            icon="Plus"
            style="margin: 5px 5px"
            size="small"
            :disabled="cfgSelectDisabled"
            @click="handleTargetAdd"
            v-hasPermi="['pricingconfig:otcoption:targetadd']"
        >新增
        </el-button>
        <el-button
            type="success"
            icon="Edit"
            size="small"
            style="margin: 5px 5px"
            :disabled="single2"
            @click="handleTargetUpdate"
            v-hasPermi="['pricingconfig:otcoption:targetedit']"
        >修改
        </el-button>
        <el-button
            type="danger"
            icon="Delete"
            style="margin: 5px 5px"
            size="small"
            :disabled="single2"
            @click="handleTargetDelete"
            v-hasPermi="['pricingconfig:otcoption:targetremove']"
        >删除
        </el-button>
      </div>

      <xTable ref="refTargetTable" refId="refTargetTable" multiple="false"
              v-loading="loading2"
              :data="targetList" width="100vw" :table-layout="'auto'"
              @selection-change="handleTargetSelectionChange"
              class="tableDragger"
      >
        <template #columList>
          <el-table-column label="序号" type="index" width="55"/>
          <el-table-column v-if="true" align="center" label="定价配置代码" prop="CFG_ID" width="120" />
          <el-table-column align="center" label="合约编号" prop="I_CODE" width="150"/>
          <el-table-column align="center" label="标的代码" prop="U_I_CODE" width="150">
          </el-table-column>
          <el-table-column align="center" label="标的名称" prop="U_I_NAME" width="150"/>
          <el-table-column align="center" label="资产类型" prop="U_A_TYPE" width="120">
            <template #default="scope">
              <dict-tag :options="A_TYPE" :value="scope.row.U_A_TYPE" spVal='*'/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="市场类型" prop="U_M_TYPE" width="120">
            <template #default="scope">
              <dict-tag :options="M_TYPE" :value="scope.row.U_M_TYPE" spVal='*'/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="价格类型" prop="SPOT_QUOTE_TYPE" width="120">
            <template #default="scope">
              <dict-tag :options="spotQuoteType" :value="scope.row.SPOT_QUOTE_TYPE" spVal='*'/>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="right" label="红利率(%)"
                           prop="DIV_NAME" width="120">
            <template #default="scope">
              <span>{{
                  scope.row.DIV_TYPE == '0' ? proxy.lsh.multiply(scope.row.DIV_VALUE, 100).toFixed(3) : scope.row.DIV_NAME
                }}</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" align="right" label="波动率(%)"
                           prop="VLS_NAME" >
            <template #default="scope">
              <span>{{
                  scope.row.VOL_TYPE == '0' ? proxy.lsh.multiply(scope.row.VOL_VALUE, 100).toFixed(3) : scope.row.VLS_NAME
                }}</span>
            </template>
          </el-table-column>

        </template>
      </xTable>
      <pagination
          v-show="targetTotal>0"
          :total="targetTotal"
          v-model:page="queryTargetParams.pageNum"
          v-model:limit="queryTargetParams.pageSize"
          style="float:right"
          @pagination="getTargetListBycgfId"
      />
    </div>

    <!-- 添加或修改 合约参数 对话框 -->
    <el-dialog :title="contractTitle" v-model="contractOpen" width="480px" :close-on-click-modal="false" draggable
               destroy-on-close append-to-body>
      <el-form ref="contractRef" :model="contractForm" :rules="contractRules" label-width="110px">
        <el-form-item label="定价配置">
          <baseCombox url="/pricing/comboBox/queryPriceCfg4Local.action?productType=OtcOption"
                      ref="cfgIdRef"
                      @change="handleCfgIdChange"
                      prop="cfgId"
                      clearable
                      valueField="cfgId" disabled
                      labelField="name"
                      size="small"
                      :style="{width: '100%'}" placeholder="定价配置" v-model="contractForm.cfgId"></baseCombox>
        </el-form-item>
        <el-form-item label="期权类型">
          <dictCombox v-model="contractForm.productType" dictType="optionType" prop="productType"
                      :disabled="contractDisabled.productTypeDisabled" size="small"></dictCombox>
        </el-form-item>
        <el-form-item label="合约编号">
          <el-input v-model="contractForm.iCode" :style="{width: '100%'}" maxlength="64" :placeholder="action=='update' ? ' ':'请输入合约编号'"
                    :disabled="contractDisabled.iCodeDisabled"></el-input>
        </el-form-item>
        <el-form-item label="资产类型">
          <dictCombox v-model="contractForm.aType" dictType="A_TYPE" prop="aType"
                      :placeholder="action=='update' ? ' ':'请选择'"
                      :disabled="contractDisabled.aTypeDisabled"
                      size="small"></dictCombox>

        </el-form-item>
        <el-form-item label="标的">

          <underlyer ref="instrumentRef" v-model="contractForm.instrument" size="small" prop="instrument"
                     :placeholder="action=='update' ? ' ':'请选择'"
                     :disabled="contractDisabled.instrumentDisabled"></underlyer>

        </el-form-item>
        <el-form-item label="计算组件" prop="dllName">
          <baseCombox url="/pricing/otcOption/queryEngineCfg.action" ref="engineCfgRef" clearable
                      :queryParam="engineConfigQueryParam"
                      valueField="ppCode"
                      labelField="ppName"
                      size="small"
                      :style="{width: '100%'}" placeholder="请选中计算组件" v-model="contractForm.dllName"></baseCombox>
        </el-form-item>
        <el-form-item label="无风险利率类型" prop="disType">
          <el-radio-group v-model="contractForm.disType" @change="handleDisTypeChange ">
            <el-radio-button :label="0" border>固定</el-radio-button>
            <el-radio-button :label="1" border>浮动</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="无风险利率(%)" :inline="true">
          <baseCombox url="/pricing/comboBox/queryIrcurveFilter.action" ref="ircurveRef" clearable
                      prop="disIrcCode" v-show="contractShow.disIrcCodeShow"
                      size="small"
                      :style="{width: '100%'}" placeholder="请输入无风险利率" v-model="contractForm.disIrcCode"></baseCombox>
          <el-col :span="12">
            <number v-model="contractForm.disIrcRate" maxlength="8" v-show="contractShow.disIrcRateShow" :style="{width: '100%'}"
                    prop='disIrcRate'
                    precision="3"></number>
          </el-col>
          <el-col :span="12">
            <dictCombox v-model="contractForm.disDayCount" v-show="contractShow.disDayCountShow" prop='disDayCount'
                        dictType="dayCounter"
                        :style="{width: '100%'}"></dictCombox>
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitContractForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>

    </el-dialog>

    <!-- 添加或修改 标的参数 对话框 -->
    <el-dialog :title="targetTitle" v-model="targetOpen" width="480px" :close-on-click-modal="false" draggable
               destroy-on-close append-to-body>
      <el-form ref="targetRef" :model="targetForm" :rules="targetRules" label-width="110px">
        <el-form-item label="定价配置" prop="cfgId">
          <baseCombox url="/pricing/comboBox/queryPriceCfg4Local.action?productType=OtcOption"
                      ref="cfgIdRef"
                      @change="handleCfgIdChange"
                      clearable
                      disabled
                      valueField="cfgId"
                      labelField="name"
                      size="small"
                      :style="{width: '100%'}" placeholder="定价配置" v-model="targetForm.cfgId"></baseCombox>
        </el-form-item>
        <el-form-item label="合约编号">
          <el-input v-model="targetForm.iCode" :style="{width: '100%'}" maxlength="64"
                    :disabled="targetDisabled.iCodeDisabled"></el-input>
        </el-form-item>
        <el-form-item label="配置指标类型">
          <dictCombox v-model="targetForm.cfgSetType" dictType="cfgSetType"
                      :disabled="targetDisabled.cfgSetTypeDisabled" @change="handleCfgSetTypeChange"
                      size="small"></dictCombox>

        </el-form-item>

        <el-form-item label="资产类型" prop="uAType" v-show="targetShow.uATypeShow">
          <dictCombox v-model="targetForm.uAType" dictType="A_TYPE" :disabled="targetDisabled.uATypeDisabled"
                      size="small"></dictCombox>
        </el-form-item>
        <el-form-item label="市场类型" v-show="targetShow.uMTypeShow">
          <dictCombox v-model="targetForm.uMType" dictType="M_TYPE" :disabled="targetDisabled.uMTypeDisabled"
                      size="small"></dictCombox>
        </el-form-item>

        <el-form-item label="标的" prop="instrument" v-show="targetShow.instrumentShow">
          <underlyer ref="targetInstrumentRef"
                     v-model="targetForm.instrument"
                     :style="{width: '100%'}"
                     :underlyerId="targetForm.instrument"
                     :disabled="targetDisabled.instrumentDisabled"></underlyer>
        </el-form-item>
        <el-form-item label="价格类型" prop="spotQuoteType">
          <dictCombox :filterKey = "filterList"
                      v-model="targetForm.spotQuoteType" dictType="spotQuoteType" size="small"></dictCombox>
        </el-form-item>
        <el-form-item label="红利率类型" prop="divType">
          <el-radio-group v-model="targetForm.divType" @change="handleDivTypeChange ">
            <el-radio-button :label="0" border>固定</el-radio-button>
            <el-radio-button :label="1" border>浮动</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="红利率(%)">
          <baseCombox url="/pricing/comboBox/queryDivyield.action"
                      ref="ircurveRef"
                      v-show="targetShow.divIrcCodeShow"
                      prop="divIrcCode"
                      clearable
                      size="small"
                      :style="{width: '100%'}" placeholder="请选择" v-model="targetForm.divIrcCode"></baseCombox>
          <el-col :span="12">

            <number v-model="targetForm.divIrcRate" v-show="targetShow.divIrcRateShow" prop='divIrcRate'
                    :style="{width: '100%'}" maxlength="8"
            precision="3"></number>
          </el-col>
          <el-col :span="12">

            <dictCombox v-model="targetForm.divDayCount" v-show="targetShow.divDayCountShow" prop='divDayCount'
                        dictType="dayCounter"
                        :style="{width: '100%'}"></dictCombox>
          </el-col>
        </el-form-item>

        <el-form-item label="波动率类型" prop="volType">
          <el-radio-group v-model="targetForm.volType" @change="handleVolTypeChange ">
            <el-radio-button :label="0" border>固定</el-radio-button>
            <el-radio-button :label="1" border>浮动</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="波动率(%)" :inline="true">

          <baseCombox url="/pricing/comboBox/queryVolsurface.action" ref="ircurveRef" clearable
                      v-show="targetShow.volIrcCodeShow" prop="volIrcCode"
                      size="small"
                      :style="{width: '100%'}" placeholder="请选择" v-model="targetForm.volIrcCode"></baseCombox>
          <el-col :span="12">
            <number v-model="targetForm.volIrcRate" v-show="targetShow.volIrcRateShow" prop='volIrcRate'
                    :style="{width: '100%'}" maxlength="8"
            precision="3"></number>
          </el-col>
          <el-col :span="12">
            <dictCombox v-model="targetForm.volDayCount" v-show="targetShow.volDayCountShow" dictType="dayCounter"
                        prop='volDayCount'
                        :style="{width: '100%'}"></dictCombox>
          </el-col>

        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTargetForm">确 定</el-button>
          <el-button @click="cancelTarget">取 消</el-button>
        </div>
      </template>

    </el-dialog>

  </div>
</template>

<script setup name="CfgOtcOption">
import {onMounted, ref, watch} from 'vue'
import {
  deleteContractCfg,
  deleteTargetParamCfg,
  insertContractCfg,
  insertTargetParamCfg,
  queryContractCfg,
  queryTargetParamCfgByPage,
  updateContractCfg,
  updateTargetParamCfg
} from '../../../api/pricingconfig/otcoption'
import {isVoid, isNotVoid} from '@/utils/util'
import { parseTime } from '@/utils/xquant'


const {proxy} = getCurrentInstance()
const {
  M_TYPE,
  A_TYPE,
  CURRENCY,
  productType,
  optionType,
  cfgSetType,
  spotQuoteType
} = proxy.useDict('M_TYPE', 'A_TYPE', 'cfgSetType', 'spotQuoteType', 'CURRENCY', 'productType', 'optionType')
const screenHeight = ref(proxy.lsh.divide(document.documentElement.clientHeight - 330, 2) + 'px')
const cfgSelectDisabled = ref(true)

const cfgRight = ref(undefined)


const queryParamCfg = ref(
    {
      isAuthor: 'true',
      productType: 'OtcOption'
    }
)

// 合约列表
const contractList = ref([])
// 标的列表
const targetList = ref([])
const selectionContractRow = ref([])
const selectionTargetRow = ref([])

const contractOpen = ref(false)
const targetOpen = ref(false)
const contractTitle = ref('')
const targetTitle = ref('')
const engineCfgRef = ref(null);

const loading = ref(false)
const loading2 = ref(false)
// id
const ids = ref([])
const ids2 = ref([])
//索引
const indexs = ref([])
const indexs2 = ref([])
//数据
const rows = ref([])
const rows2 = ref([])

const single = ref(true)
const multiple = ref(true)
const single2 = ref(true)
const multiple2 = ref(true)
const contractTotal = ref(0)
const targetTotal = ref(0)

const defaultSelectCfgId = ref(null);

const targetInstrumentRef = ref(null);

const engineConfigQueryParam = computed(()=>{
  if(action.value == 'add'){
    contractForm.value.dllName = undefined
  }
  return {
    productType: contractForm.value.productType
  }
})

const action = ref('')

const mainCfgIdRef = ref(null)

const data = reactive({
  contractForm: {
    iCode: undefined,
    cfgId: undefined,
    productType: undefined,
    aType: null,
    instrument: undefined,
    uICode: undefined,
    uAType: undefined,
    uMType: undefined,
    dllName: undefined,
    disType: 0,
    disIrcCode: undefined,
    disIrcRate: undefined,
    disValue: undefined,
    disDayCount: undefined
  },
  targetForm: {
    cfgId: undefined,
    iCode: undefined,
    cfgSetType: undefined,
    spotQuoteType: undefined,
    instrument: undefined,
    uICode: undefined,
    uAType: undefined,
    uMType: undefined,
    volType: 0,
    volIrcCode: undefined,
    volIrcRate: undefined,
    volValue: undefined,
    volDayCount: undefined,
    divType: 0,
    divIrcCode: undefined,
    divIrcRate: undefined,
    divValue: undefined,
    divDayCount: undefined,

  },
  contractShow: {
    disIrcCodeShow: false,
    disIrcRateShow: true,
    disDayCountShow: true,
  },
  targetShow: {
    uATypeShow: false,
    uMTypeShow: false,
    instrumentShow: false,
    divIrcCodeShow: false,
    divIrcRateShow: true,
    divDayCountShow: true,
    volIrcCodeShow: false,
    volIrcRateShow: true,
    volDayCountShow: true,

  },
  contractDisabled: {
    iCodeDisabled: false,
    productTypeDisabled: false,
    aTypeDisabled: false,
    instrumentDisabled: false,
    dllName: false,
  },
  targetDisabled: {
    iCodeDisabled: false,
    cfgSetTypeDisabled: false,
    uATypeDisabled: false,
    uMTypeDisabled: false,
    instrumentDisabled: false
  },
  queryConfigParams: {
    pageNum: 1,
    pageSize: 10,
    cfgId: null
  },
  queryConfigRules: {
    cfgId: [{required: true, message: '定价配置不能为空', trigger: 'blur'}]
  },
  contractRules: {
    dllName: [{required: true, message: '计算组件不能为空', trigger: 'blur'}],
    disType: [{required: true, message: '无风险利率类型不能为空', trigger: 'blur'}],
    disIrcCode: [{required: false, message: '无风险利率曲线不能为空', trigger: 'blur'}],
    disIrcRate: [{required: true, message: '无风险利率不能为空', trigger: 'blur'}],
    disDayCount: [{required: true, message: '计息基准不能为空', trigger: 'blur'}],
  },
  targetRules: {
    cfgSetType: [{required: true, message: '配置指标类型不能为空', trigger: 'blur'}],
    instrument: [{required: true, message: '标的不能为空', trigger: 'blur'}],
    spotQuoteType: [{required: true, message: '价格类型不能为空', trigger: 'blur'}],
    uAType: [{required: true, message: '资产类型不能为空', trigger: 'blur'}],
    divType: [{required: true, message: '红利率类型不能为空', trigger: 'blur'}],
    divIrcCode: [{required: false, message: '红利率曲线不能为空', trigger: 'blur'}],
    divIrcRate: [{required: true, message: '红利率不能为空', trigger: 'blur'}],
    divDayCount: [{required: true, message: '计息基准不能为空', trigger: 'blur'}],
    volType: [{required: true, message: '波动率类型不能为空', trigger: 'blur'}],
    volIrcCode: [{required: false, message: '波动率曲线不能为空', trigger: 'blur'}],
    volIrcRate: [{required: true, message: '波动率不能为空', trigger: 'blur'}],
    volDayCount: [{required: true, message: '计息基准不能为空', trigger: 'blur'}],

  },
  queryTargetParams: {
    pageNum: 1,
    pageSize: 10,
    cgfId: undefined
  }
})
const filterList = ref(null);
const {
  queryTargetParams,
  queryConfigParams,
  contractForm,
  targetForm,
  contractRules,
  targetRules,
  typeGroup,
  contractShow,
  targetShow,
  contractDisabled,
  targetDisabled
} = toRefs(data)


/**  定价配置 选中按钮 */
function handleCfgIdChange(val) {
  contractForm.value.cfgId = val
  if (val) {
    cfgSelectDisabled.value = false
  } else {
    cfgSelectDisabled.value = true
    contractList.value = []
    contractTotal.value = 0
    targetList.value = []
    targetTotal.value = 0
  }
  getContractCfgList()
  getTargetListBycgfId()


  //遍历下拉框中的数据，根据当前选中的cfgId得到CfgRight
  mainCfgIdRef.value.dataList.forEach(element => {
    if (contractForm.value.cfgId == element.cfgId) {
      cfgRight.value = element.cfgRight
      return
    }
  })

}


/** 查询按钮 */
function handleContractCfgQuery() {
  getContractCfgList()
  getTargetListBycgfId()
}

/** 查询定价配置列表 */
function getContractCfgList() {
  if (proxy.isNotVoid(queryConfigParams.value.cfgId)) {
    loading.value = true
    queryContractCfg(queryConfigParams.value).then(response => {
      contractList.value = response.list
      contractTotal.value = response.total
      loading.value = false
    })
  }
}

/**合约 新增按钮操作 */
function handleContractAdd() {

  if (cfgRight.value === '1') {
    proxy.$modal.alertError('没有权限新增数据')
    return
  }
  reset()
  contractOpen.value = true
  contractDisabled.value.iCodeDisabled = false
  contractDisabled.value.productTypeDisabled = false
  contractDisabled.value.aTypeDisabled = false
  contractDisabled.value.instrumentDisabled = false
  contractTitle.value = '添加合约参数'
  contractForm.value.cfgId = queryConfigParams.value.cfgId
  action.value = 'add'
  handleDisTypeChange(0)

}

/**标的 新增按钮操作 */
function handleTargetAdd() {
  if (cfgRight.value === '1') {
    proxy.$modal.alertError('没有权限新增数据')
    return
  }
  resetTarget()
  targetOpen.value = true
  targetForm.value.cfgSetType = '2'
  handleCfgSetTypeChange('2')
  targetForm.value.uAType = 'SPT_S'
  targetDisabled.value.iCodeDisabled = false
  targetDisabled.value.cfgSetTypeDisabled = false
  targetDisabled.value.uATypeDisabled = false
  targetDisabled.value.uMTypeDisabled = false
  targetDisabled.value.instrumentDisabled = false
  targetTitle.value = '添加标的参数'
  targetForm.value.cfgId = queryConfigParams.value.cfgId
  action.value = 'add'
  handleDivTypeChange(0);
  handleVolTypeChange(0);
}

/**
 *
 * 合约  修改按钮操作
 * */
function handleContractUpdate() {
  if (cfgRight.value === '1') {
    proxy.$modal.alertError('没有权限修改该数据')
    return
  }



  action.value = 'update'
  contractOpen.value = true
  contractTitle.value = '修改合约参数'
  setTimeout(function () {
    reset()
    let data = rows.value[0]
    contractDisabled.value.iCodeDisabled = true
    contractDisabled.value.productTypeDisabled = true
    contractDisabled.value.aTypeDisabled = true
    contractDisabled.value.instrumentDisabled = true

    contractForm.value.cfgId = data.CFG_ID
    contractForm.value.iCode = data.I_CODE == '*' ? '' : data.I_CODE
    contractForm.value.productType = data.PRODUCT_TYPE
    contractForm.value.aType = data.U_A_TYPE
    contractForm.value.uICode = data.U_I_CODE
    contractForm.value.uAType = data.U_A_TYPE
    contractForm.value.uMType = data.U_M_TYPE

    if (!proxy.lsh.isEqual(contractForm.value.uICode, '*')) {
      contractForm.value.instrument = data.U_I_CODE + ',' + data.U_A_TYPE + ',' + data.U_M_TYPE
      proxy.$refs['instrumentRef'].setValue(data.U_I_CODE + ',' + data.U_A_TYPE + ',' + data.U_M_TYPE)

    }
    contractForm.value.dllName = data.PP_CODE
    contractForm.value.disType = data.DIS_TYPE
    contractForm.value.disValue = data.DIS_VALUE
    if (data.DIS_TYPE == '0') {
      contractForm.value.disIrcRate = proxy.lsh.multiply(data.DIS_VALUE, 100).toFixed(4)
      contractForm.value.disIrcRate = proxy.lsh.multiply(data.DIS_VALUE, 100).toFixed(5)
      contractForm.value.disDayCount = data.DIS_DAYCOUNT
    } else {
      contractForm.value.disIrcCode = data.DIS_VALUE
    }
    handleDisTypeChange(data.DIS_TYPE)
  }, 1 * 100)//延迟100毫米
}

/**
 *
 * 标的  修改按钮操作
 * */
function handleTargetUpdate() {
  if (cfgRight.value === '1') {
    proxy.$modal.alertError('没有权限修改该数据')
    return
  }
  action.value = 'update'
  targetOpen.value = true
  targetTitle.value = '修改标的参数'
  setTimeout(function () {
    resetTarget()
    let data = rows2.value[0]
    targetDisabled.value.iCodeDisabled = true
    targetDisabled.value.cfgSetTypeDisabled = true
    targetDisabled.value.uATypeDisabled = true
    targetDisabled.value.uMTypeDisabled = true
    targetDisabled.value.instrumentDisabled = true

    targetForm.value.cfgId = data.CFG_ID
    targetForm.value.iCode = data.I_CODE == '*' ? '' : data.I_CODE
    if (!proxy.lsh.isEqual(data.U_I_CODE, '*')) {
      targetForm.value.instrument = data.U_I_CODE + ',' + data.U_A_TYPE + ',' + data.U_M_TYPE
      proxy.$refs['targetInstrumentRef'].setValue(data.U_I_CODE + ',' + data.U_A_TYPE + ',' + data.U_M_TYPE)
      targetForm.value.cfgSetType = '1'
    } else if (data.U_A_TYPE != '*') {
      targetForm.value.uAType = data.U_A_TYPE
      targetForm.value.uMType = data.U_M_TYPE == '*' ? '' : data.U_M_TYPE
      targetForm.value.cfgSetType = '2'
    } else {
      targetForm.value.cfgSetType = '3'
    }
    handleCfgSetTypeChange(targetForm.value.cfgSetType)
    targetForm.value.spotQuoteType = data.SPOT_QUOTE_TYPE

    targetForm.value.divType = data.DIV_TYPE
    targetForm.value.divValue = data.DIV_VALUE
    if (data.DIV_TYPE == '0') {
      targetForm.value.divIrcRate = proxy.lsh.multiply(data.DIV_VALUE, 100).toFixed(4)
      targetForm.value.divIrcRate = proxy.lsh.multiply(data.DIV_VALUE, 100).toFixed(3)
      targetForm.value.divDayCount = data.DIV_DAYCOUNT
    } else {
      targetForm.value.divIrcCode = data.DIV_VALUE
    }
    handleDivTypeChange(data.DIV_TYPE)
    targetForm.value.volType = data.VOL_TYPE
    targetForm.value.volValue = data.VOL_VALUE
    if (data.VOL_TYPE == '0') {
      targetForm.value.volIrcRate = proxy.lsh.multiply(data.VOL_VALUE, 100).toFixed(4)
      targetForm.value.volIrcRate = proxy.lsh.multiply(data.VOL_VALUE, 100).toFixed(3)
      targetForm.value.volDayCount = data.VOL_DAYCOUNT
    } else {
      targetForm.value.volIrcCode = data.VOL_VALUE
    }
    handleVolTypeChange(data.VOL_TYPE)

  }, 1 * 100)//延迟100毫米
}

/**
 *
 * 修改/新增   保存操作
 * */
function submitContractForm() {
  proxy.$refs.contractRef.validate(valid => {
    if (valid) {
      var param = {}
      param.iCode = contractForm.value.iCode
      if (isVoid(contractForm.value.iCode)) {
        param.iCode = '*'
      }
      param.cfgId = queryConfigParams.value.cfgId
      param.productType = contractForm.value.productType
      if (isVoid(contractForm.value.productType)) {
        param.productType = '*'
      }
      param.aType = contractForm.value.aType
      if (isVoid(contractForm.value.aType)) {
        param.aType = '*'
      }
      if (isVoid(contractForm.value.instrument)) {
        param.uICode = '*'
        param.uAType = '*'
        param.uMType = '*'
      } else {
        param.uICode = proxy.lsh.split(contractForm.value.instrument, ',')[0]
        param.uAType = proxy.lsh.split(contractForm.value.instrument, ',')[1]
        param.uMType = proxy.lsh.split(contractForm.value.instrument, ',')[2]
      }
      param.dllName = contractForm.value.dllName

      param.disType = contractForm.value.disType
      param.disValue = contractForm.value.disValue
      param.disDayCount = contractForm.value.disDayCount
      if (contractForm.value.disType == '0') {
        param.disValue = proxy.lsh.divide(contractForm.value.disIrcRate, 100).toFixed(5)
        param.disIrcRate = contractForm.value.disIrcRate
      } else {
        param.disValue = contractForm.value.disIrcCode
        param.disIrcCode = contractForm.value.disIrcCode
      }
      if (action.value == 'update') {
        updateContractCfg(param).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess('修改成功')
            contractOpen.value = false
            getContractCfgList()
          } else {
            proxy.$modal.msgError(response.msg)
          }
        })
      } else {
        insertContractCfg(param).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess('新增成功')
            contractOpen.value = false
            getContractCfgList()
          } else {
            proxy.$modal.msgError(response.msg)
          }
        })
      }
    }
  })
}

/**
 *
 * 修改/新增   保存操作
 * */
function submitTargetForm() {
  proxy.$refs.targetRef.validate(valid => {
    if (valid) {
      var param = {}
      param.iCode = targetForm.value.iCode
      if (proxy.lsh.isNull(targetForm.value.iCode) || proxy.lsh.isEmpty(targetForm.value.iCode) || targetForm.value.iCode == undefined) {
        param.iCode = '*'
      }
      param.cfgId = queryConfigParams.value.cfgId

      param.cfgSetType = targetForm.value.cfgSetType
      if (targetForm.value.cfgSetType == '1') {
        param.uICode = proxy.lsh.split(targetForm.value.instrument, ',')[0]
        param.uAType = proxy.lsh.split(targetForm.value.instrument, ',')[1]
        param.uMType = proxy.lsh.split(targetForm.value.instrument, ',')[2]
      } else if (targetForm.value.cfgSetType == '3') {
        param.uICode = '*'
        param.uAType = '*'
        param.uMType = '*'
      } else {
        param.uICode = '*'
        param.uAType = targetForm.value.uAType
        param.uMType = targetForm.value.uMType
        if (isVoid(targetForm.value.uMType)) {
          param.uMType = '*'
        }
      }
      param.spotQuoteType = targetForm.value.spotQuoteType
      if (proxy.lsh.isNull(targetForm.value.spotQuoteType) || proxy.lsh.isEmpty(targetForm.value.spotQuoteType) || targetForm.value.spotQuoteType == undefined) {
        param.spotQuoteType = '*'
      }
      param.divType = targetForm.value.divType
      param.divValue = targetForm.value.divValue
      param.divDayCount = targetForm.value.divDayCount
      if (targetForm.value.divType == '0') {
        param.divValue = proxy.lsh.divide(targetForm.value.divIrcRate, 100).toFixed(4)
        param.divValue = proxy.lsh.divide(targetForm.value.divIrcRate, 100).toFixed(5)
        param.divIrcRate = targetForm.value.disIrcRate
      } else {
        param.divValue = targetForm.value.divIrcCode
        param.divIrcCode = targetForm.value.divIrcCode
      }
      param.volType = targetForm.value.volType
      param.volValue = targetForm.value.volValue
      param.volDayCount = targetForm.value.volDayCount
      if (targetForm.value.volType == '0') {
        param.volValue = proxy.lsh.divide(targetForm.value.volIrcRate, 100).toFixed(4)
        param.volValue = proxy.lsh.divide(targetForm.value.volIrcRate, 100).toFixed(5)
        param.volIrcRate = targetForm.value.volIrcRate
      } else {
        param.volValue = targetForm.value.volIrcCode
        param.volIrcCode = targetForm.value.volIrcCode
      }

      if (action.value == 'update') {
        updateTargetParamCfg(param).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess('修改成功')
            targetOpen.value = false
            getTargetListBycgfId()
          } else {
            proxy.$modal.msgError(response.msg)
          }
        })
      } else {
        insertTargetParamCfg(param).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess('新增成功')
            targetOpen.value = false
            getTargetListBycgfId()
          } else {
            proxy.$modal.msgError(response.msg)
          }
        })
      }
    }
  })
}

/** 根据 标的 查询按钮 */
function handleTargetQuery() {
  getTargetListBycgfId()
}

/** 标的 查询 */
function getTargetListBycgfId() {
  loading.value = true
  queryTargetParams.value.cfgId = queryConfigParams.value.cfgId
  queryTargetParamCfgByPage(queryTargetParams.value).then(response => {
    targetList.value = response.list
    targetTotal.value = response.total
    loading.value = false
  })
}


/**
 *
 * 合约 多选框  选中数据
 * */
function handleContractSelectionChange(selection) {
  if (selection.length == 0) {
    ids.value = []
    indexs.value = []
  } else {
    ids.value = selection.map(item => item.CFG_ID)
    indexs.value = selection.map(item => item.index)
    rows.value = selection.map(item => item)
  }
  single.value = selection.length != 1
  multiple.value = !selection.length
  if (selection.length == 1) {
    return
  }
  if (selection.length != 1) {

  }
}

/**
 *  标的
 *  多选框  选中数据
 * */
function handleTargetSelectionChange(selection) {
  if (selection.length == 0) {
    ids2.value = []
    indexs2.value = []
  } else {
    ids2.value = selection.map(item => item.CFG_ID)
    indexs2.value = selection.map(item => item.index)
    rows2.value = selection.map(item => item)
  }
  single2.value = selection.length != 1
  multiple2.value = !selection.length
  if (selection.length == 1) {
    return
  }

}


/** 合约 删除按钮操作 */
function handleContractDelete() {
  if (cfgRight.value === '1') {
    proxy.$modal.alertError('没有权限删除该数据')
    return
  }
  var params = {
    cfgId: rows.value[0].CFG_ID,
    productType: rows.value[0].PRODUCT_TYPE,
    iCode: rows.value[0].I_CODE,
    aType: rows.value[0].A_TYPE,
    uICode: rows.value[0].U_I_CODE,
    uAType: rows.value[0].U_A_TYPE,
    uMType: rows.value[0].U_M_TYPE,
  }
  proxy.$modal.confirm('是否确认删除此配置？').then(function () {
    return deleteContractCfg(params)
  }).then(() => {
    getContractCfgList()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {
  })
}

/** 标的 删除按钮操作 */
function handleTargetDelete() {
  if (cfgRight.value === '1') {
    proxy.$modal.alertError('没有权限删除该数据')
    return
  }
  let data = rows2.value[0]
  var params = {
    cfgId: data.CFG_ID,
    iCode: data.I_CODE,
    uICode: data.U_I_CODE,
    uAType: data.U_A_TYPE,
    uMType: data.U_M_TYPE,
  }
  proxy.$modal.confirm('是否确认删除此配置？').then(function () {
    return deleteTargetParamCfg(params)
  }).then(() => {
    getTargetListBycgfId()
    proxy.$modal.msgSuccess('删除成功')
  }).catch(() => {
  })
}

/** 配置指标类型 选中 */
function handleCfgSetTypeChange(val) {
  if (val == '1') {//标的
    targetShow.value.uATypeShow = false
    targetShow.value.uMTypeShow = false
    targetShow.value.instrumentShow = true
    targetRules.value.uAType[0].required = false
    targetRules.value.instrument[0].required = true
  } else if (val == '2') {//资产类型
    targetShow.value.uATypeShow = true
    targetShow.value.uMTypeShow = true
    targetShow.value.instrumentShow = false
    targetRules.value.uAType[0].required = true
    targetRules.value.instrument[0].required = false
  } else if (val == '3') {//全部
    targetShow.value.uATypeShow = false
    targetShow.value.uMTypeShow = false
    targetShow.value.instrumentShow = false
    targetRules.value.uAType[0].required = false
    targetRules.value.instrument[0].required = false
    //当选择全部时，只能选择最新价格和定盘价格
    filterList.value = [0,1]
  }
}

/** 合约 贴现率类型按钮 */
function handleDisTypeChange(val) {
  if (val == '0') {//固定
    contractShow.value.disIrcCodeShow = false
    contractShow.value.disIrcRateShow = true
    contractShow.value.disDayCountShow = true
    contractRules.value.disIrcCode[0].required = false
    contractRules.value.disIrcRate[0].required = true
    contractRules.value.disDayCount[0].required = true
  } else {//浮动
    contractShow.value.disIrcCodeShow = true
    contractShow.value.disIrcRateShow = false
    contractShow.value.disDayCountShow = false
    contractRules.value.disIrcCode[0].required = true
    contractRules.value.disIrcRate[0].required = false
    contractRules.value.disDayCount[0].required = false
  }
}

/** 红利类型按钮 */
function handleDivTypeChange(val) {

  if (val == '0') {//固定
    targetShow.value.divIrcCodeShow = false
    targetShow.value.divIrcRateShow = true
    targetShow.value.divDayCountShow = true
    targetRules.value.divIrcCode[0].required = false
    targetRules.value.divIrcRate[0].required = true
    targetRules.value.divDayCount[0].required = true
  } else {//浮动
    targetShow.value.divIrcCodeShow = true
    targetShow.value.divIrcRateShow = false
    targetShow.value.divDayCountShow = false
    targetRules.value.divIrcCode[0].required = true
    targetRules.value.divIrcRate[0].required = false
    targetRules.value.divDayCount[0].required = false
  }
}

/** 波动类型按钮 */
function handleVolTypeChange(val) {
  if (val == '0') {//固定
    targetShow.value.volIrcCodeShow = false
    targetShow.value.volIrcRateShow = true
    targetShow.value.volDayCountShow = true
    targetRules.value.volIrcCode[0].required = false
    targetRules.value.volIrcRate[0].required = true
    targetRules.value.volDayCount[0].required = true
  } else {//浮动
    targetShow.value.volIrcCodeShow = true
    targetShow.value.volIrcRateShow = false
    targetShow.value.volDayCountShow = false
    targetRules.value.volIrcCode[0].required = true
    targetRules.value.volIrcRate[0].required = false
    targetRules.value.volDayCount[0].required = false
  }
}



/** 取消按钮 */
function cancel() {
  contractOpen.value = false
  reset()
}

/** 取消按钮 */
function cancelTarget() {
  targetOpen.value = false
  resetTarget()
}


/** 表单重置 */
function reset() {
  contractForm.value = {
    iCode: undefined,
    cfgId: undefined,
    productType: undefined,
    aType: null,
    uICode: undefined,
    uAType: undefined,
    uMType: undefined,
    dllName: undefined,
    disType: 0,
    disIrcCode: undefined,
    disIrcRate: undefined,
    disValue: undefined,
    disDayCount: undefined
  }
  proxy.resetForm('contractRef')
}

/** 表单重置 */
function resetTarget() {
  targetForm.value = {
    cfgId: undefined,
    iCode: undefined,
    cfgSetType: undefined,
    spotQuoteType: undefined,
    instrument: undefined,
    uICode: undefined,
    uAType: undefined,
    uMType: undefined,
    volType: 0,
    volIrcCode: undefined,
    volIrcRate: undefined,
    volValue: undefined,
    volDayCount: undefined,
    divType: 0,
    divIrcCode: undefined,
    divIrcRate: undefined,
    divValue: undefined,
    divDayCount: undefined,

  }
  proxy.resetForm('targetRef')
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('xxx/export', {
    ...queryParams.value
  }, `用户组信息${new Date().getTime()}.xlsx`)
}

/** 导出按钮操作 */
function handleExportAll() {
  proxy.download('xxx/export', Object.assign({
    ...queryParams.value
  }, {pageSize: ''}), `用户组信息${new Date().getTime()}.xlsx`)
}

/** 监听默认配置 */
watch(defaultSelectCfgId, val => {
  queryConfigParams.value.cfgId = val;
  cfgSelectDisabled.value = false
  getContractCfgList()
  getTargetListBycgfId()
})

watch(()=>data.targetForm.instrument,(val)=>{
  var date = parseTime(new Date());
  if (isVoid(val)){
    return
  }
  proxy.$refs['targetInstrumentRef'].getDailyPrice({
    instrumentId: val,
    startDate: date,
  }).then((price) => {
    if (price) {
      filterList.value = price.filterList
    }
  })
})

watch(()=>data.targetForm.uAType,(val)=>{
  if (isVoid(val)){
    return
  }
  filterList.value = [0,1,2,3]
  // DP_SET 当且仅当在基金和股票时存在
  if (!["SPT_CEF", "SPT_ETF", "SPT_LOF", "SPT_OEF", "SPT_MMF", "FWD_BDS","SPT_S"].includes(val)) {
    filterList.value = [0,1,3]
  }
  //TIR_SERIES表没有DP_AVG  利率行情没有平均价
  if (["SPT_NTD", "SPT_REPO", "SPT_TMD", "SPT_DED", "SPT_IBOR", "SPT_LN", "SPT_CF"].includes(val)) {
    filterList.value = [0,1,2]
  }
})



</script>
<style scoped >
.otcoptionWrapper{
  height:inherit;
  display: flex;
  flex-direction: column;
  width: 100%;
}
.app-container{
  flex:1;
  display: flex;
  flex-direction: column;
}
.pagination-container1 /deep/.el-pagination {
    position: inherit !important;
    bottom: 0px !important;
    float: right !important;
  }
.tableDragger{
  flex:1 0 180px;
  min-width:200px;
  /*width: 100% !important;*/
}
</style>

